package top.fengyulou.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.fengyulou.common.UserUtils;
import top.fengyulou.config.SysConfig;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private SysConfig sysConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户数据
        JSONObject user = UserUtils.getUser(request);
        if (ObjectUtils.isEmpty(user)) {
            response.sendRedirect(sysConfig.getDomainName() + SysConfig.INDEX);
            return false;
        }
        request.setAttribute(UserUtils.LOGIN_USER, user);
        return true;
    }
}
